﻿using System;

namespace Tiny.Imaging.Filter.PixelLibrary
{
    public struct Rgba
    {
        public int A;
        public int B;
        public int G;
        public int R;

        public static Rgba Parse(int pixel)
        {
            var result = new Rgba
                             {
                                 A = ((pixel >> 24) & 0xff),
                                 R = ((pixel >> 16) & 0xff),
                                 G = ((pixel >> 8) & 0xff),
                                 B = (pixel & 0xff),
                             };

            return result;
        }

        public int ToInteger()
        {
            return (A << 24) | (R << 16) | (G << 8) | B;
        }

        public Hsl ToHsl()
        {
            int max = Math.Max(R, Math.Max(G, B));
            int min = Math.Min(R, Math.Min(G, B));

            float r = R/255.0f;
            float g = G/255.0f;
            float b = B/255.0f;
            float dMax = max/255.0f;
            float dMin = min/255.0f;

            float h = 0, s = 0, l = (dMax + dMin)/2.0f;

            if (max != min)
            {
                float diff = dMax - dMin;
                s = l > 0.5f ? diff/(2 - dMax - dMin) : diff/(dMax + dMin);
                if (max == R)
                {
                    h = (g - b)/diff + (g < b ? 6 : 0);
                }
                else if (max == G)
                {
                    h = (b - r)/diff + 2;
                }
                else
                {
                    h = (r - g)/diff + 4;
                }
            }

            return new Hsl {H = h/6, S = s, L = l};
        }
    }
}